﻿using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Tracing;
using TfsStatus.Models;
using TfsStatus.Tfs;

namespace TfsStatus.Controllers
{
	public class TfsChangesetController : ApiController
	{
		[]
		public ChangeSetHistory Get(DateTime since)
		{
			var changeSets = ChangeSetProvider.GetChangesetsSince(since);

			var history = new ChangeSetHistory
			{
				ChangeSetsByUser = changeSets.GroupBy(c => c.UserName).ToDictionary(g => g.Key, g => g.ToList()),
				Since = since
			};
			if (history.ChangeSetsByUser.Count < 1)
				history.ErrorMessage = "No changesets since " + since.ToString();

			TraceInfo(
				String.Format("Found changesets for {0} users since {1}", history.ChangeSetsByUser.Keys.Count, since));

			return history;
		}

		protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
		{
			base.Initialize(controllerContext);
			ChangeSetProvider.TfsConnected += ChangeSetProvider_TfsConnected;
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				ChangeSetProvider.TfsConnected -= ChangeSetProvider_TfsConnected;
			}
			finally
			{
				base.Dispose(disposing);
			}
		}

		private void ChangeSetProvider_TfsConnected(object sender, EventArgs e)
		{
			TraceInfo("TFS Connected");
		}

		private void TraceInfo(string message)
		{
			Configuration.Services.GetTraceWriter().Info(
				Request, "TfsChangesetController", message);
		}
	}
}

